<template>
  <div class="components-trend">
    <div class="flow-title">
      <div class="flow-title-left">
        <div class="line" />
        <div class="text">
          {{ $t('dataAnalysis.flowTrend') }}
        </div>
      </div>
      <div class="flow-title-right">
        <div
          v-if="isAuth('flow:trend:export')"
          class="default-btn primary-btn export-btn"
          @click="exportCategory()"
        >
          {{ $t("order.export") }}
        </div>
      </div>
    </div>
    <!-- 单项选择 -->
    <div class="radio-box flow-form">
      <el-form @submit.prevent>
        <el-form-item :label="$t('dataAnalysis.pageBrowsing') + ':'">
          <el-radio-group v-model="typeValue">
            <el-radio
              class="radio-item"
              :label="1"
            >
              {{ $t('dataAnalysis.numberOfVisitors') }}
            </el-radio>
            <el-radio
              v-if="dateType !== 4"
              class="radio-item"
              :label="2"
            >
              {{ $t('dataAnalysis.newVisitor') }}
            </el-radio>
            <el-radio
              class="radio-item"
              :label="3"
            >
              {{ $t('dataAnalysis.pageviews') }}
            </el-radio>
            <el-radio
              v-if="dateType !== 4"
              class="radio-item"
              :label="4"
            >
              {{ $t('dataAnalysis.stayTime') }}
            </el-radio>
            <el-radio
              class="radio-item"
              :label="5"
            >
              {{ $t('dataAnalysis.perVisits') }}
            </el-radio>
            <el-radio
              v-if="dateType !== 4"
              class="radio-item"
              :label="6"
            >
              {{ $t('dataAnalysis.lossRate') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('dataAnalysis.transactionConversion')">
          <el-radio-group v-model="typeValue">
            <el-radio
              class="radio-item"
              :label="7"
            >
              {{ $t('dataAnalysis.paidNumbers') }}
            </el-radio>
            <el-radio
              class="radio-item"
              :label="8"
            >
              {{ $t('dataAnalysis.vToP') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <!-- 单项选择 -->

    <div class="content-container">
      <!-- 选择显示不同端的数据 -->
      <div class="plat">
        <el-radio-group
          v-model="systemType"
        >
          <el-radio-button
            v-model="radioCheck"
            :label="0"
          >
            {{ $t('date.a') }}
          </el-radio-button>
          <el-radio-button
            v-model="radioCheck"
            :label="1"
          >
            PC
          </el-radio-button>
          <el-radio-button
            v-model="radioCheck"
            :label="2"
          >
            H5
          </el-radio-button>
          <el-radio-button
            v-model="radioCheck"
            :label="3"
          >
            {{ $t('sysManagement.miniProgramSmall') }}
          </el-radio-button>
          <el-radio-button
            v-model="radioCheck"
            :label="4"
          >
            {{ $t('dataAnalysis.android') }}
          </el-radio-button>
          <el-radio-button
            v-model="radioCheck"
            :label="5"
          >
            IOS
          </el-radio-button>
        </el-radio-group>
        <div class="t-explain-item">
          {{ ['',$t('dataAnalysis.numberOfVisitors')
              ,$t('dataAnalysis.newVisitor'),$t('dataAnalysis.pageviews'),$t('dataAnalysis.stayTime'),$t('dataAnalysis.perVisits')
              ,$t('dataAnalysis.lossRate'),$t('dataAnalysis.paidNumbers'),$t('dataAnalysis.vToP')][typeValue] }}
        </div>
      </div>
      <!-- /选择显示不同端的数据 -->

      <!-- 图表 -->
      <div class="chart">
        <div
          id="i-chart"
          style="width:100%;height:300px;"
        />
      </div>
    </div>
    <!-- /图表 -->
  </div>
</template>

<script setup>
import { Debounce } from '@/utils/debounce'
import { isAuth } from '@/utils'
import Big from 'big.js'
import * as $echarts from 'echarts'
import { ElLoading, ElMessage } from 'element-plus'

const radioCheck = ref(0)

const props = defineProps({
  sysType: { // 系统类型
    type: Number,
    default: 0
  },
  dateType: {
    type: Number,
    default: 0
  },
  dateRange: {
    type: Array,
    default: () => ([])
  }
})
const emit = defineEmits(['changeSysType'])

watch([() => props.dateRange, () => props.sysType], () => {
  getFlowTrendData()
})

const typeValue = ref(1) // 默认单项选择为第一项
watch(typeValue, (flowType) => {
  switchEchart(flowType)
})

const systemType = computed({
  get () {
    return props.sysType
  },
  set (val) {
    emit('changeSysType', val)
  }
})

// 切换趋势图实时改变
const flowTrendData = ref([]) // 流量趋势数据
const eChartTitleArray = ref([]) // Echart图列表
const currEchartTitle = ref('') // 当前Echart的名字
const switchEchart = (flowType) => {
  dataArray.value = []
  currEchartTitle.value = eChartTitleArray.value[flowType - 1]
  switch (flowType) {
    case 1:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].userNums)
      }
      break
    case 2:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].newUser)
      }
      break
    case 3:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].visitNums)
      }
      break
    case 4:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].averageStopTime)
      }
      break
    case 5:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].averageVisitNums)
      }
      break
    case 6:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].lossUserRate)
      }
      break
    case 7:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].payUser)
      }
      break
    case 8:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(new Big(flowTrendData.value[i].payRate).times(100).toFixed(2))
      }
      break
    default:
      for (let i = 0; i < flowTrendData.value.length; i++) {
        dataArray.value.push(flowTrendData.value[i].userNums)
      }
      break
  }
  getOneEchart()
}
// 获取趋势图相关数据
const dataArray = ref([]) // Echart显示具体数据
const timeArray = ref([]) // Echart X轴下方显示的具体时间
const getFlowTrendData = () => {
  // 遍历Echart标题名
  const ele = document.getElementsByClassName('radio-item')
  for (let j = 0, len = ele.length; j < len; j++) {
    eChartTitleArray.value.push(ele[j].innerText)
  }
  // 默认第一个(访客数)
  currEchartTitle.value = eChartTitleArray.value[0]
  // 请求接口
  http({
    url: http.adornUrl('/platform/flowAnalysis/flowTrend'),
    method: 'get',
    params: http.adornParams({
      timeType: props.dateType,
      start: props.dateRange[0] || null,
      end: props.dateRange[1] || null,
      systemType: props.sysType
    })
  }).then(({ data }) => {
    if (data) {
      flowTrendData.value = []
      timeArray.value = []
      dataArray.value = []
      for (let i = 0; i < data.length; i++) {
        flowTrendData.value.push(data[i])
        timeArray.value.push(data[i].dateTime)
      }
      switchEchart(typeValue.value)
    }
  })
}

// 获取第一部分Echart数据图
const getOneEchart = () => {
  const myChart = $echarts.init(document.getElementById('i-chart'))
  const option = {
    color: ['#155bd4'],
    tooltip: {
      trigger: 'axis',
      backgroundColor: '#fff',
      padding: 8,
      textStyle: { // 提示框浮层的文本样式。
        fontSize: '12px',
        fontWeight: 400,
        color: '#33333',
        opacity: 1
      },
      extraCssText: 'box-shadow:0px 1px 11px rgba(213, 220, 226, 0.73);width:180px;height:62px',
      formatter: function (params) {
        // params数组可以了解一下，一条线和多条线都是数组
        let html = ''
        for (const i in params) {
          const param = params[i]
          // echarts日期格式化api
          const date = param.name
          html += `<span style="color: #999999">${date}</span><br /><div style="margin-top: 12px;display: flex;align-items: center;"><i style="display: inline-block;width: 6px;height: 6px;background-color: #0058FF;margin-right: 9px;border-radius: 50%;"></i><span style=" display:inline-block;">${param.seriesName}：${param.data}</span></div>`
        }
        return html
      },
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeArray.value
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          color: ['#E0E6F1'],
          width: 1,
          type: 'solid'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        name: currEchartTitle.value,
        type: 'line',
        smooth: true,
        itemStyle: {
          lineStyle: {
            color: '#155bd4'
          },
          // 点的颜色
          color: '#155bd4'
        },
        areaStyle: {
          color: new $echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(21, 91, 212, 0.5)'
          }, {
            offset: 1,
            color: '#ffffff'
          }])
        },
        data: dataArray.value
      }
    ]
  }
  myChart.setOption(option)
  myChart.resize()
  window.addEventListener('resize', function () {
    myChart.resize()
  })
}

// 导出
const exportCategory = Debounce(() => {
  const loading = ElLoading.service({
    lock: true,
    target: '.trend',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/flowAnalysis/flowTrendExport'),
    method: 'get',
    params: http.adornParams({
      timeType: props.dateType,
      start: props.dateRange[0] || null,
      end: props.dateRange[1] || null
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('dataAnalysis.flowTrend') + '.xlsx'
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('shop.exportSuccess'),
      type: 'success',
      duration: 1500
    })
  }).catch(() => {
    loading.close()
  })
})

</script>

<style lang="scss" scoped>
.components-trend {
  .flow-title {
    margin-top: 50px;
  }
  .content-container {
    padding: 20px;
    border: 1px solid #eee;
    // 选择显示不同端的数据
    .plat {
      // eslint-disable-next-line vue-scoped-css/no-unused-selector
      .el-radio-button {
        :deep(.el-radio-button__inner) {
          width: 80px;
          text-align: center;
          padding: 0;
          height: 32px;
          line-height: 32px;
          font-size: 12px;
        }
      }
      :deep(.el-radio-button:first-child),
      :deep(.el-radio-button:last-child) {
        .el-radio-button__inner {
          border-radius: 0;
        }
      }
      // eslint-disable-next-line vue-scoped-css/no-unused-selector
      .is-active {
        :deep(.el-radio-button__inner) {
          color: #155bd4;
          background-color: rgba(21,91,212, .1);
        }
      }
    }
    .t-explain-item {
      display: inline-block;
      margin-left: 100px;
      font-size: 12px;
      font-weight: 400;
      color: #999999;
      &::before {
        display: inline-block;
        content: '';
        width: 18px;
        height: 8px;
        background: #155bd4;
        border-radius: 8px;
        margin-right: 10px;
      }
    }

    .chart {
      padding: 10px;
    }
  }
  :deep(.export-load) {
    top: -50% !important;
  }

}
</style>
